/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.text.*;
import java.util.Enumeration;
import java.util.Locale;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import util.Data_variante;
/**
 *
 * @author dragonboy
 */
public class Comment_show extends HttpServlet {

    String [] App={"All","Blog","Photo","Album","Feed","Q&amp;A (Product)","","","","","","","","","","","123Mua (Product)","Mp3-Song (Product)","Mp3-Video (Product)","Mp3-Playlist (Product)","Link","Live"};
    String [] TypeCmt = {"Normal","Unsured Spam","Spam","Bad","Unsure Polictics", "Unsure Common"};
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, org.apache.lucene.queryParser.ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
//        String [] Doc_splited;
//        Enumeration enum_para = request.getParameterNames();
//        while(enum_para.hasMoreElements()){
//            System.out.println("name is: "+ (String)enum_para.nextElement());
//        }
        
        //System.out.println(request.getQueryString());
        String datestr = request.getParameter("date");
        String typeCmt = request.getParameter("Type");
        String type_app = request.getParameter("app");
//        String check_delete_all = "check_delete_all";
//        String Check_all_approve = "check_all_approve";
        
        DecimalFormat df = new DecimalFormat("#,###");
        df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ITALIAN));
        String indexDateDir = Data_variante.dir_index + "/" + datestr;
        File file = new File(indexDateDir);
        FSDirectory dir = FSDirectory.open(file);
        //To do query index
        Searcher searcher
            = new IndexSearcher(dir);
        QueryParser parser = new QueryParser(Version.LUCENE_34, "OwnerID", new StandardAnalyzer(Version.LUCENE_34));
        //parser.setAllowLeadingWildcard(true);
        String command = "Type:"+typeCmt+" AND Status:0";
        Query myquery = parser.parse(command);
        int hitsPerPage = 300;
        int pagesize = 10;
        TopDocs results = searcher.search(myquery,300);
        int totalHit = results.totalHits;
        int nums_gotten = (totalHit > hitsPerPage)? hitsPerPage: totalHit;
        int nums_page = (nums_gotten % pagesize == 0)? (nums_gotten/pagesize): ((nums_gotten/pagesize)+1);
        ScoreDoc[] hits = results.scoreDocs;
        
        //to do show result
        if(type_app.equals("All")){
             type_app = "0";   
        }
        int paranum = Integer.valueOf(type_app);
        int typenum = Integer.valueOf(typeCmt);
        out.println("<script type=\"text/javascript\">"
                + "function check_checkbox(value,ischecked){"
                + "document.getElementById(\"table-body\")."
                + "}"
                + "</script>");
        out.println("<script type=\"text/javascript\">"
                    +"$(document).ready(function() {"
                    +"$(\"#content-action-table tbody\").quickPager( {"
                    +"pageSize:"+ pagesize+","
                    +"currentPage: 1,"
                    +"holder: \".pagination\""
                    //+"holder:\"\""
                    +"});"
                    +"});"
                   +"</script>");
//        for(ScoreDoc hit : hits){
//            check_delete_all += "-" +String.valueOf(hit.doc);
//            Check_all_approve += "-" + String.valueOf(hit.doc);
//        }
        out.println("<div id=\"header-tip\"></div>"
                +"<form name=\"HanderContentComment\" action=\"submit_action\" method=\"POST\" onsubmit=\"xmlhttpPost(\'submit_action\', \'HanderContentComment\', \'content-action\', \'\'); return false;\">"
                +"Total: " + df.format(totalHit)
                +"<input type=\"submit\" value=\"" + Data_variante.submit_button_value +"\" name=\"submit["+datestr+"]\" class=\"handersubmit\">"
                +"<input type=\"hidden\" value=\""+ type_app +"\" name=\"Appcheck["+ type_app +"]\">"
                +"<input type=\"hidden\" value=\""+ typeCmt +"\" name=\"Typecheck["+ typeCmt +"]\">"
                + "<br class=\"clear-all\"><br class=\"clear-all\">"
                +"<table id=\"content-action-table\" cellpadding=\"0\" cellspacing=\"0\">"
                +"<thead>"
                +"<tr>"
                +"<th class=\"table-the-first\">"+ Data_variante.table_col1_name +"</th>"
                +"<th class=\"table-1\">"+ Data_variante.table_col2_name + "</th>"
                +"<th class=\"table-7\">"+ Data_variante.table_col8_name +"</th>"
                +"<th class=\"table-2\">"+ Data_variante.table_col3_name + "</th>"
                +"<th class=\"table-3\">"+ Data_variante.table_col4_name(typeCmt) +"&nbsp;<input type=\"checkbox\" id=\"check_delete_all\" name=\"check_all_delete\" onclick=\"SetSel(this);\" ></th>"
                +"<th class=\"table-4\">"+ Data_variante.table_col5_name(typeCmt) +"&nbsp;<input type=\"checkbox\" id=\"check_approve_all\" name=\"check_all_approve\" onclick=\"SetSel(this);\"></th>"
                +"<th class=\"table-5\">"+ Data_variante.table_col6_name + "</th>"
                +"<th class=\"table-6\">"+ Data_variante.table_col7_name +"</th>"
                +"</tr>"
                +"</thead>"
                +"<tbody id=\"table-body\">");
        Date date;
        int count = 0;
        for(ScoreDoc hit : hits) {
              count++;
              Document d = searcher.doc(hit.doc);
              date = new Date(Long.valueOf(d.get("Time"))*1000);
              out.println("<tr>"
                + "<td class=\"table-the-first\">"+ count + "</td>"
                + "<td >"+ TypeCmt[typenum] +"</td>"
                + "<td >"+ d.get("OwnerID") +"</td>"
                + "<td><div class=\"content-action-table-comment\">"+ d.get("Comment") +"</div></td>"
                + "<td><input type=\"radio\" value=\"0\" class=\"check_remove_id\" name=\"check["+ hit.doc +"]\"></td>"
                + "<td><input type=\"radio\" value=\"1\" class=\"check_approve_id\" name=\"check["+ hit.doc +"]\"></td>"
                + "<td>"+ dateFormat.format(date) +"</td>"
                + "<td >"+ App[paranum] +"</td>"
                + "</tr");
        }
        out.println("</tbody>"
                    +"</table>"
                    //+"<br class=\"clear-all\">"
                    //+"<input type=\"checkbox\" value=\"" + Data_variante.submit_button_value +"\" name=\"submit["+datestr+"."+typeCmt+"]\" class=\"handersubmit\">"
                    +"<div id=\"delete-all-div\" class=\"deleteall\"><input type=\"checkbox\" id=\"All_delete\" name=\"Delete_all\" onclick=\"SetSel(this);\" >"+ " <b>Delete All</b>" +"</div>"
                    +"<br class=\"clear-all\">"
                    +"</form>"
                    +"<div class=\"pagination\">"
                    //+"</div>"
                    +"</div>");
        out.println("<script type=\"text/javascript\">"
                + "$(function() {"
                + "$(\".pagination\").paginate({"
                + "count                   :"+ nums_page +","
                + "start                   : 1,"
                + "display                 : 10,"
                + "border                  : true,"
                + "border_color            : '#fff',"
                + "text_color              : '#fff',"
                + "background_color        : 'black',"
                + "border_hover_color      : '#ccc',"
                + "text_hover_color        : '#000',"
                + "background_hover_color  : '#fff', "
                + "images                  : false,"
                + " mouse                   : 'press',"
                + "onChange                : function(page){"
                + "$('._current','#table-body').removeClass('_current').hide();"
                + "$('.page'+page).addClass('_current').show();"
                + "var element = $(\"#check_delete_all\",'#content-action-table');"
                + "element[0].checked = false;"
                + "element = $(\"#check_approve_all\",'#content-action-table');"
                + "element[0].checked = false;"
                + "}"
                + "});});"
                + "</script>");
        out.println("<script type=\"text/javascript\">"
                + "function SetSel(elem){"
                    //+ "var elems = document.getElementsByTagName(\"input\");"
                    + "var name = elem.name;"
                    + "var elems;"
                    + "var elem_checkbox;"
                    + "var elem_checkbox1;"
                    + "if(elem.getAttribute('name') === \"check_all_delete\"){"
                        + "elem_checkbox = $(\"#check_approve_all\",'#content-action-table');"
                        + "elem_checkbox1 = $(\"#All_delete\",'#delete-all-div');"
                        + "elems = $(\"._current :input\",'#table-body');"
                    + "}else if(elem.getAttribute('name') === \"check_all_approve\"){"
                        + "elem_checkbox = $(\"#check_delete_all\",'#content-action-table');"
                        + "elem_checkbox1 = $(\"#All_delete\",'#delete-all-div');"
                        + "elems = $(\"._current :input\",'#table-body');"
                    + "}else{"
                        + "elem_checkbox = $(\"#check_approve_all\",'#content-action-table');"
                        + "elem_checkbox1 = $(\"#check_delete_all\",'#content-action-table');"
                        + "elems = $(\"#table-body :input\");"
                    + "}"
                    + "elem_checkbox[0].checked = false;"
                    + "elem_checkbox1[0].checked = false;"
                    + "var currentState = elem.checked;"
                    + "var elemsLength = elems.length;"
                    + "for(i=0; i<elemsLength; i++){"
                        //+ "if(elems[i].type === \"checkbox\"){"
                        //    + "elems[i].checked = false;  "
                        //+ "}"
                        + "if(elems[i].type === \"radio\"){"
                            + "if((elem.getAttribute('name') === \"check_all_delete\" && elems[i].getAttribute('class') ===\"check_remove_id\")|| (elem.getAttribute('name') === \"check_all_approve\" && elems[i].getAttribute('class') ===\"check_approve_id\")){"  
                                + "elems[i].checked = currentState;"
                            + "}"
                            + "else if(elem.getAttribute('name') === \"Delete_all\" && elems[i].getAttribute('class') ===\"check_remove_id\"){"
                                + "elems[i].checked = currentState;"
                            + "}else{"
                                + "elems[i].checked = false;"
                            + "}"
                        + "}"
                    + "}"
                    + "elem.checked = currentState;"
                + "}"
                + "</script>");
        out.close();
        searcher.close();
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (org.apache.lucene.queryParser.ParseException ex) {
            Logger.getLogger(Comment_show.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (org.apache.lucene.queryParser.ParseException ex) {
            Logger.getLogger(Comment_show.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
